package com.xin.data.simbapesa.analysis.libs

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.os.Looper
import android.provider.Settings
import androidx.core.content.edit
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.xin.data.simbapesa.api.U

import java.util.concurrent.Executors

@SuppressLint("StaticFieldLeak")
object AdIdLib {

    private const val PREF_NAME = U.URL_MAIN_PRODUCT
    private const val KEY_AID = "AID"
    private const val KEY_AD_ENABLE = "ENABLE"

    @Volatile
    private var _adEnabled: Int = 0

    @Volatile
    private var _adId: String = ""

    private lateinit var _sp: SharedPreferences
    private lateinit var _context: Context

    private val executor = Executors.newSingleThreadExecutor()

    fun init(context: Application) {
        _context = context.applicationContext
        _sp = _context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)

        if (_adId.isBlank()) {
            _adId = _sp.getString(KEY_AID, "") ?: ""
            _adEnabled = _sp.getInt(KEY_AD_ENABLE, 0)
        }

        if (_adId.isBlank()) {
            fetchAdvertisingId()
        }
    }

    private fun fetchAdvertisingId() {
        executor.execute {
            try {
                if (Looper.myLooper() == Looper.getMainLooper()) {
                    println("[AdvertIdLib] ERROR: Cannot call fetchAdvertisingId() on the main thread")
                    return@execute
                }

                if (!checkGooglePlayServices(_context)) return@execute

                val adClient = AdvertisingIdClient.getAdvertisingIdInfo(_context)
                _adId = adClient.id ?: ""
                _adEnabled = if (adClient.isLimitAdTrackingEnabled) 1 else 0

                _sp.edit(commit = true) {
                    putString(KEY_AID, _adId)
                    putInt(KEY_AD_ENABLE, _adEnabled)
                }
            } catch (e: Exception) {
                println("[AdvertIdLib] Failed to fetch Advertising ID: ${e.message}")
            }
        }
    }

    private fun checkGooglePlayServices(context: Context): Boolean {
        val resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
        return if (resultCode == ConnectionResult.SUCCESS) {
            true
        } else {
            println("[AdvertIdLib] Google Play Services not available: $resultCode")
            false
        }
    }

    fun adId(): String = _adId

    fun adEnabled(): Int = _adEnabled

    fun androidId(): String {
        val androidID = Settings.System.getString(
            _context.contentResolver,
            Settings.Secure.ANDROID_ID
        )
        return if (androidID.isNullOrBlank() || androidID.contains("00000000")) {
            System.currentTimeMillis().toString()
        } else {
            androidID
        }
    }
}